<?php
/**
 * Administracia katalogu produktov
 */
class AdminCatalogue extends Page {

	private $items_not_null;

	/**
     * Metoda na zobrazenie triedy
     *
     */
    public function show() {
        global $db, $r;

		parent::show();

		$this->path[] = array(
			"admin/catalogue",
			i18n::t("cat_catalogue")
			);

        $id   = $r["arg"][3] + 0;

   		//zamazanie kategorie
        if (($r["arg"][2] == "del-category") && ($id)) {

            self::removeCategory($id);
            rLocate("admin/catalogue");
            return;
        }


       //posuvanie

        if (in_array($r["arg"][2], array("up-category", "down-category"))) {

            $this->moveItem($r["arg"][3],$r["arg"][2]);

            rLocate("admin/catalogue");
            return;
        }


        //pridanie a uprava

        if (in_array($r["arg"][2], array("edit-category", "add-category"))) {
            // $id = content.id

            //odoslanie formulara

            if (($_POST["action"] == "change") || ($_POST["action"] == "add")) {
				$posted = $this->processForm();
            }


            //zobrazenie formulara

            //pridavanie
            if ($r["arg"][2] == "add-category") {

                $this->path[] = array(
					"admin/catalogue",
					i18n::t("cat_newcategory")
					);
                $content["add"] = true;


                if (!$posted) {

                    // default language
                    $content["lang"] = $r["lang"];
                }

            // editacia
            } elseif ($r["arg"][2] == "edit-category") {


                if (!$posted) {
                    $content = $db->getRow("
                        SELECT * FROM c_categories
                        WHERE id = $id AND lang = '{$r["lang"]}'
                    ");
                }

                if (!$content) {
                    rLocate("admin/catalogue");
                    return;
                }

                $content["language"] = $r["i18n"]["languages"][$content["lang"]];

                // path
                $this->path[] = array(
                    "catalogue/$id",
                    $r["lang"] => $content["title"]
                );
                $this->path[] = array(
                    "",
                    i18n::t("cat_cat_edit")
                );
            }




            $tree = new RTree("c_categories", "id", "parent_id");

            $tree->setQuery("tree", "
                SELECT t1.%ID%, t1.title
                FROM %TABLE% t1
                LEFT JOIN %TABLE% t2
                   ON t2.%PARENT_ID% = t1.%ID%
                  AND t2.lang = '{$r["lang"]}'
                WHERE t1.%PARENT_ID% = %d
                  AND t1.lang = '{$r["lang"]}'
                GROUP BY t1.%ID%, t1.weight, t1.title
                ORDER BY t1.weight, t1.%ID%
            ");

            $categories = $tree->getSimpleTree(0, 0, true);

            foreach ($categories as &$item) {
                $item["depth"]++;
                $title = $item["title"];
                $item["title"] = array(
                    "admin" => true,
                    $r["admin_lang"] => $item["title"]
                );
            }


            array_unshift($categories, array(
                "id"    => 0,
                "title" => array(
                    "admin" => true,
                    "sk"    => "KOREŇOVÁ KATEGÓRIA",
                    "en"    => "ROOT CATEGORY"
                ),
                "depth" => 0
            ));


            //editacia
            if ($r["arg"][2] == "edit-category") {

                for ($i = 0; $i < count($categories); $i++) {
                    if ($categories[$i]["id"] == $id) {
                        $depth = $categories[$i]["depth"];
                        unset($categories[$i]);
                        $i++;
                        while ($categories[$i]["depth"] > $depth) {
                            unset($categories[$i]);
                            $i++;
                        }
                        break;
                    }
                }
            }

            $images=rDirList($r[root]."/data/cats",array("\.jpg"),array("-thumb\.jpg"));

            $this->tpl->assign("categories", $categories);

            $this->tpl->assign("content", $content);

            $this->tpl->assign("images",$images);
            $this->tpl->assign("path",$this->path);

            $this->tpl->display("admin-catalogue-category.tpl");
            return;
        }



		//zmazanie sablony
        if (($r["arg"][2] == "del-template") && ($id)) {

            $db->query("
                DELETE FROM c_templates
                WHERE id = $id;

                DELETE FROM c_product_details
                WHERE product_id = $id;
            ");

            rLocate("admin/catalogue/templates");
            return;
        }


        //zmazanie produktu
        if (($r["arg"][2] == "del-product") && ($id)) {

            $category = $db->getCell("
                SELECT category_id FROM c_products
                WHERE id = $id;
            ");

            $db->query("
                DELETE FROM c_products
                WHERE id = $id;

                DELETE FROM c_product_details
                WHERE product_id = $id;
            ");

            Catalogue::deleteAllImages($id);

            rLocate("catalogue/$category");
            return;
        }


        // posuvanie sablony

        if (in_array($r["arg"][2], array("up-template", "down-template", "up-product", "down-product"))) {

           $this->moveTemplate();
        }


        // posuvanie poloziek produktu

        if (in_array($r["arg"][2], array("up-item", "down-item"))) {

			$this->moveProduct();
        }


        // pridanie/mazanie

        if (in_array($r["arg"][2], array("add-template", "edit-template", "add-product", "edit-product"))) {

            list($action, $type) = explode("-", $r["arg"][2]);

            $load_template = (($type == "product") && ($action == "add") && ($id));

            if (($type == "template") || ($load_template)) {
                $this->path[] = array(
                    "admin/catalogue/templates",
                    i18n::t("cat_templates")
                );
            } elseif ($type == "product") {
                $this->path[] = array(
                    "",
                    i18n::t("cat_catalogue")
                );
            }

			//odoslany formular
            if (($_POST["action"] == "change") || ($_POST["action"] == "add")) {

          		$posted = $this->process($type);
            }


           //formular

            $items_to_add = $this->cfg["catalogue_product_inputs"];

            $do_load_template = (($load_template) && (!$posted));

            // pridanie
            if ($action == "add") {

                // nova sablona
                if ($type == "template") {
                    $this->path[] = array(
                        "",
                        i18n::t("cat_templates_add")
                    );

                // novy produkt
                } elseif (($type == "product") && (!$load_template)) {
                    array_pop($this->path);
                    $this->path[] = array(
                        "",
                        i18n::t("cat_newproduct")
                    );
                }

                $content["add"] = true;


            }

            //editacia
            if (($action == "edit") || ($load_template)) {


                if (!$posted) {
                    if ($load_template) $table = "c_templates";
                    else $table = "c_{$type}s";

                    $content = $db->getRow("
                        SELECT * FROM $table
                        WHERE id = $id AND lang = '{$r["lang"]}'
                    ");

                    foreach ($r["i18n"]["languages"] as $lang => $language) {
                        $content["detail_title"][$lang] = $db->getCol("
                            SELECT title FROM c_product_details
                            WHERE product_id = {$content["id"]} AND lang = '$lang'
                            ORDER BY weight
                        ");
                    }

                    $content["detail_value"] = $db->getCol("
                        SELECT value FROM c_product_details
                        WHERE product_id = {$content["id"]} AND lang = '{$r["lang"]}'
                        ORDER BY weight
                    ");

                    $content["detail_unit"] = $db->getCol("
                        SELECT unit FROM c_product_details
                        WHERE product_id = {$content["id"]} AND lang = '{$r["lang"]}'
                        ORDER BY weight
                    ");

                    if (!$content["id"]) {
                        rLocate("admin/catalogue/templates");
                        return;
                    }

                    if ($load_template) {
                        $content["template"] = $content["title"];
                        unset($content["title"]);
                        unset($content["text"]);
                    }
                }

                $content["language"] = $r["i18n"]["languages"][$content["lang"]];

                if ($load_template) {


                    if ($posted) {
                        $content["template"] = $db->getCell("
                            SELECT title FROM c_templates
                            WHERE id = $id AND lang = '{$r["lang"]}'
                        ");
                    }

                    $content["add"] = true;
//{$content["template"]}
                    $this->path[] = array(
                        "",
                        i18n::t("cat_newproduct")." ".$content["template"]
                    );
                } else {
                    // path
                    $this->path[] = array(
                        "admin/catalogue/add-produt/$id",
                        $r["lang"] => $content["title"]
                    );

            }}


            $tree = new RTree("c_categories", "id", "parent_id");

            $tree->setQuery("tree", "
                SELECT t1.%ID%, t1.title
                FROM %TABLE% t1
                LEFT JOIN %TABLE% t2
                   ON t2.%PARENT_ID% = t1.%ID%
                  AND t2.lang = '{$r["lang"]}'
                WHERE t1.%PARENT_ID% = %d
                  AND t1.lang = '{$r["lang"]}'
                GROUP BY t1.%ID%, t1.weight, t1.title
                ORDER BY t1.weight, t1.%ID%
            ");

            $categories = $tree->getSimpleTree(0, 0, true);

            foreach ($categories as &$item) {
                $title = $item["title"];
                $item["title"] = array(
                    "admin" => true,
                    $r["admin_lang"] => $item["title"]
                );
            }

            if ($type == "template") {
                array_unshift($categories, array(
                    "id"    => 0,
                    "title" => array(
                        "admin" => true,
                        "sk"    => "---",
                        "en"    => "---"
                    ),
                    "depth" => 0
                ));
            }
            $this->tpl->assign("categories",  $categories);

            //detaily
            $items_to_add = $this->cfg["catalogue_product_inputs"];
            $details = array();
            $n = 1;

            for ($i = 0; $i < count($content["detail_value"]); $i++) {
                if ((!$posted) || (in_array($i, $this->items_not_null))) {
                    $title = array();
                    foreach ($r["i18n"]["languages"] as $lang => $language) {
                        $title[$lang] = $content["detail_title"][$lang][$i];
                    }
                    $details[] = array(
                        "title"  => $title,
                        "value"  => $content["detail_value"][$i],
                        "unit"   => $content["detail_unit"][$i],
                        "number" => $n++
                    );
                }
            }
            for ($i = 0; $i < $items_to_add; $i++) {
                $details[] = array(
                    "title"  => array(),
                    "value"  => "",
                    "unit"   => "",
                    "number" => $n++
                );
            }
//rPrint($details);
            $this->tpl->assign("details",  $details);

            $this->tpl->assign("content",  $content);

            $this->tpl->assign($type, true);
             $this->tpl->assign("path",$this->path);

            $this->tpl->display("admin-catalogue-details.tpl");
            return;
        }


        //vypis sablon
        if ($r["arg"][2] == "templates") {

            $this->path[] = array(
                "admin/catalogue/templates",
                i18n::t("cat_templates")
            );

            $templates = $db->getArrRow("
                SELECT * FROM c_templates
                WHERE lang = '{$r["lang"]}'
                ORDER BY weight
            ");

            $this->tpl->assign("templates", $templates);

            $this->tpl->display("admin-catalogue-templates.tpl");
            return;
        }


		//vypis kategorii
        $this->listing();
        return;

    }


	/**
	 * Metoda na zmazanie kategorie podla id
	 *
	 * @param int $id id kategorie
	 */
    private function removeCategory($id) {
        global $db, $r;

		//kategoria
        $item = $db->getRow("
            SELECT * FROM c_categories
            WHERE id = $id AND lang = '{$r["lang"]}'
        ");
        $weight = $item["weight"];

       //bratia
        $syblings = $db->getArrRow("
            SELECT * FROM c_categories
            WHERE parent_id = {$item["parent_id"]}
              AND weight > $weight
              AND lang = '{$r["lang"]}'
            ORDER BY weight
        ");

       //deti
        $children = $db->getArrRow("
            SELECT * FROM c_categories
            WHERE parent_id = $id AND lang = '{$r["lang"]}'
            ORDER BY weight
        ");

        $query = "";

        // insert the children in place of their parent
        foreach ($children as $child) {
            $query .= "
                UPDATE c_categories SET
                    parent_id   = {$item["parent_id"]},
                    weight      = $weight
                WHERE id = {$child["id"]};
            ";
            $weight++;
        }

        // move the syblings lower
        foreach ($syblings as $sybling) {
            $query .= "
                UPDATE c_categories SET
                    weight      = $weight
                WHERE id = {$sybling["id"]};
            ";
            $weight++;
        }
        $db->query($query);

        // finally we can delete the menu item
        $db->query("
            DELETE FROM c_categories
            WHERE id = $id
        ");
    }

    /**
     * Metoda na psouvanie poloziek vramci kategorie
     *
     * @param int $id id kategorie
     * @param string $direction smer posunu
     */
    private function moveItem($id,$direction) {
    	global $r,$db;

    	$category1 = $db->getRow("
                SELECT id, weight FROM c_categories WHERE id = $id
            ");

            $category2 = $db->getRow("
                SELECT id, weight FROM c_categories
                WHERE weight " . ($direction == "up-category" ? "<" : ">") . " {$category1["weight"]}
                ORDER BY weight " . ($direction == "up-category" ? "DESC" : "") . "
            ");

            if ($category2) {
                $db->query("
                    UPDATE c_categories SET weight = {$category2["weight"]}
                    WHERE id = {$category1["id"]};

                    UPDATE c_categories SET weight = {$category1["weight"]}
                    WHERE id = {$category2["id"]};
                ");
            }

          //  die('x');
    }

	/**
	 * Administracny vypis kategorii
	 */
    private function listing() {
    	global $db,$r;

    	//kategorie
        $tree = new RTree("c_categories", "id", "parent_id");

        $tree->setQuery("tree", "
            SELECT t1.%ID%, t1.title
            FROM %TABLE% t1
            LEFT JOIN %TABLE% t2
               ON t2.%PARENT_ID% = t1.%ID%
              AND t2.lang = '{$r["lang"]}'
            WHERE t1.%PARENT_ID% = %d
              AND t1.lang = '{$r["lang"]}'
            GROUP BY t1.%ID%, t1.title, t1.weight
            ORDER BY t1.weight, t1.%ID%
        ");

        $categories = $tree->getSimpleTree(0, 0, true);

        foreach ($categories as &$c) {
            $c["up"]   = true;
            $c["down"] = true;

            $c["products"] = $db->getCell("
                SELECT COUNT(id) FROM c_products
                WHERE category_id = {$c["id"]} AND lang = '{$r["lang"]}'
            ");
        }
        $this->tpl->assign("categories", $categories);

        //produkty bez kategorie
        $products = $db->getArrRow("
            SELECT * FROM c_products
            WHERE NOT category_id IN (SELECT id FROM c_categories) AND lang = '{$r["lang"]}'
        ");
        $this->tpl->assign("products", $products);

		$this->tpl->assign("path",$this->path);
        $this->tpl->display("admin-catalogue-list.tpl");

    }

	/**
	 * Spracovanie odoslaneho formulara
	 */
    private function processForm() {
    	global $db,$r;

				$id   = $r["arg"][3] + 0;


                foreach (array("title", "text") as $a) {
                    if (!get_magic_quotes_gpc()) {
                        $_POST[$a] =addslashes($_POST[$a]);
                    }
                    $_POST[$a] = trim($_POST[$a]);
                }

 				foreach ($r["i18n"]["languages"] as $lang => $language)
                	if ($_POST["title_{$lang}"] == "")  { $error["sk"][] = i18n::t("c_title"); }



                if ($error) {
                    $this->tpl->assign("error", array(
					i18n::t("c_please") . " ".implode(", ", $error["sk"]) . "."
					)); // oznamenie o chybe

                    $content = $_POST;
                    $posted = true;



                } else {



                    if ($_POST["action"] == "change") {


                        $db->query("
                            UPDATE c_categories SET
                                title = '{$_POST["title"]}',
                                text  = '{$_POST["text"]}',
								image = '{$_POST["image"]}'
                            WHERE id = $id AND lang = '{$r["lang"]}'
                        ");



                        $old_item = $db->getRow("
                            SELECT * FROM c_categories
                            WHERE id = $id
                        ");


                        if ($old_item["parent_id"] != $_POST["parent_id"]) {

                            $weight = $db->getCell("
                                SELECT MAX(weight) FROM c_categories
                                WHERE parent_id = {$_POST["parent_id"]}
                            ") + 1;

                            $db->query("
                                UPDATE c_categories SET
                                    parent_id   = {$_POST["parent_id"]},
                                    weight      = $weight
                                WHERE id = $id
                            ");

                        }




                    } elseif ($_POST["action"] == "add") {
                        $id = $db->getCell("
                            SELECT NEXTVAL('c_categories_id_seq')
                        ");
                        $weight = $db->getCell("
                            SELECT MAX(weight) FROM c_categories
                            WHERE parent_id = {$_POST["parent_id"]}
                        ") + 1;


                        $query = "";
                        foreach ($r["i18n"]["languages"] as $lang => $language) {

                            $query .= "
                                INSERT INTO c_categories (
                                    id, parent_id, weight, lang, title, text
                                ) VALUES (
                                    $id,
                                    '{$_POST["parent_id"]}',
                                    $weight,
                                    '$lang',
                                    '{$_POST["title_{$lang}"]}',
                                    '{$_POST["text_{$lang}"]}'
                                );
                            ";
                        }
                        $db->query($query);

                    }



                    rLocate("admin/catalogue");
                    return;
                }

                return $posted;

    }

    /**
     * Metoda na zmenu pozicie sablony
     */
    private function moveTemplate() {
    	global $db,$r;

    	 list($direction, $type) = explode("-", $r["arg"][2]);
    	 $id = $r["arg"][3] + 0;

            $object1 = $db->getRow("
                SELECT id, weight FROM c_{$type}s WHERE id = $id AND lang = '{$r["lang"]}'
            ");

            $object2 = $db->getRow("
                SELECT id, weight FROM c_{$type}s
                WHERE weight " . ($direction == "up" ? "<" : ">") . " {$object1["weight"]} AND lang = '{$r["lang"]}'
                ORDER BY weight " . ($direction == "up" ? "DESC" : "") . "
            ");

            if ($object2) {
                $db->query("
                    UPDATE c_{$type}s SET weight = {$object2["weight"]}
                    WHERE id = {$object1["id"]} AND lang = '{$r["lang"]}';

                    UPDATE c_{$type}s SET weight = {$object1["weight"]}
                    WHERE id = {$object2["id"]} AND lang = '{$r["lang"]}';
                ");
            }

           // die('xxx');

            if ($type == "template") {
                rLocate("admin/catalogue/templates");

            } elseif ($type == "product") {
                $category = $db->getCell("
                    SELECT category_id FROM c_products
                    WHERE id = $id AND lang = '{$r["lang"]}';
                ");
                rLocate("catalogue/$category");
            }
            return;

    }

	/**
	 * Metoda na zmenu pozicie produktu
	 */
    private function moveProduct() {
    	global $r,$db;

    	     list($direction, $type) = explode("-", $r["arg"][2]);

            $product_id = $r["arg"][3] + 0;
            $item_id    = $r["arg"][4] + 0;

            $object1 = $db->getRow("
                SELECT id, weight FROM c_product_details WHERE id = $item_id
            ");

            $object2 = $db->getRow("
                SELECT id, weight FROM c_product_details
                WHERE weight " . ($direction == "up" ? "<" : ">") . " {$object1["weight"]}
                  AND product_id = $product_id
                ORDER BY weight " . ($direction == "up" ? "DESC" : "") . "
            ");

            if ($object2) {
                $db->query("
                    UPDATE c_product_details SET weight = {$object2["weight"]}
                    WHERE id = {$object1["id"]};

                    UPDATE c_product_details SET weight = {$object1["weight"]}
                    WHERE id = {$object2["id"]};
                ");
            }

            rLocate("catalogue/product/$product_id");
            return;

    }

    /**
     * Spracovanie formulara
     *
     * @param string $type typ objektu
     */
    private function process($type) {
		global $db,$r;

		$id   = $r["arg"][3] + 0;

		       $this->items_not_null = array();

                foreach ($r["i18n"]["languages"] as $lang => $language) {
                    foreach ($_POST["detail_title"][$lang] as $i => &$item) {
                        if (!get_magic_quotes_gpc()) $item = addslashes($item);
                        $item = trim($item);
                        if ($item) $this->items_not_null[$i] = true;
                        unset($item);
                    }
                }
                foreach (array("detail_value", "detail_unit") as $arr) {
                    foreach ($_POST[$arr] as $i => &$item) {
                        if (!get_magic_quotes_gpc()) $item = addslashes($item);
                        $item = trim($item);
                        if ($item) $this->items_not_null[$i] = true;
                        unset($item);
                    }
                }
                $this->items_not_null = array_keys($this->items_not_null);
                sort($this->items_not_null);

                foreach (array("title", "text") as $item) {
                    if (!get_magic_quotes_gpc()) $_POST[$item] = addslashes($_POST[$item]);
                    $_POST[$item] = trim($_POST[$item]);
                    unset($item);
                }

                if ($_POST["title"] == "") {
                   i18n::t("c_title");
                }

                if (($type == "template") && (!$this->items_not_null)) {
                    $error["sk"][] = i18n::t("c_items");
                }


               //chyby
                if (($error) || ($_POST["more-items"] == "yes")) {
                    if ($error) {
                        $this->tpl->assign("error", array(
							i18n::t("c_please") . " ".implode(", ", $error["sk"]) . "."
							)); // oznamenie o chybe
                    }

                    $content = $_POST;
                    $posted = true;


                //zmeny v DB
                } else {

                    $query = "";


                    // update the record

                    if ($_POST["action"] == "change") {

                        $query .= "
                            UPDATE c_{$type}s SET
                                title       = '{$_POST["title"]}',
                                text        = '{$_POST["text"]}',
								price		= '{$_POST["price"]}',
								currency    = '{$_POST["currency"]}'
                            WHERE id = $id AND lang = '{$r["lang"]}';
                        ";


                        $query .= "
                            DELETE FROM c_product_details
                            WHERE product_id = $id;
                        ";


                   //vlozit

                    } elseif ($_POST["action"] == "add") {



                        $id = $db->getCell("
                            SELECT NEXTVAL('c_products_id_seq')
                        ");
                        $weight = $db->getCell("
                            SELECT MAX(weight) FROM c_{$type}s
                        ") + 1;

                        if ($_POST["category_id"]==0) $_POST["category_id"]="NULL";
                        if (empty($_POST["price"])) $_POST["price"]="NULL";

                        foreach ($r["i18n"]["languages"] as $lang => $languages) {
                            if ($type == "template") {
                                $query .= "
                                    INSERT INTO c_templates (id, category_id, weight, lang, title, text, price, currency)
                                    VALUES (
                                        $id, {$_POST["category_id"]}, $weight, '$lang',
                                        '{$_POST["title_$lang"]}', '{$_POST["text_$lang"]}',{$_POST["price"]},'{$_POST["currency"]}'
                                    );
                                ";
                            } elseif ($type == "product") {



                                $query .= "
                                    INSERT INTO c_products (id, category_id, weight, lang, title, text, price, currency)
                                    VALUES (
                                        $id, {$_POST["category_id"]}, $weight, '$lang',
                                        '{$_POST["title_$lang"]}', '{$_POST["text_$lang"]}',{$_POST["price"]},'{$_POST["currency"]}'
                                    );
                                ";
                            }
                        }
                    }



                    $weight = 1;

                    foreach ($this->items_not_null as $i) {
                        $detail_id = $db->getCell("
                            SELECT NEXTVAL('c_product_details_id_seq')
                        ");

                        foreach ($r["i18n"]["languages"] as $lang => $languages) {
                            $query .= "
                                INSERT INTO c_product_details (id, product_id, weight, lang, title, value, unit)
                                VALUES (
                                    $detail_id, $id, $weight, '$lang',
                                    '{$_POST["detail_title"][$lang][$i]}',
                                    '{$_POST["detail_value"][$i]}',
                                    '{$_POST["detail_unit"][$i]}'
                                );
                            ";
                        }
                        $weight++;
                    }

                    $db->query($query);

                 // die('x');

                    if ($type == "template") {
                        rLocate("admin/catalogue/templates");
                    } elseif ($type == "product") {
                        rLocate("catalogue/product/$id");
                    }
                    return;

                }

                return $posted;

    }
}

?>
